<template>
  <!-- 权限管理 -->
  <div class="page-padding-bg w100 h100" style="box-sizing: border-box;height: calc(100% - 42px);">

    <div class="permissions h100">

      <!-- <div class="l-tree">
      <lay-tree :data="treeList" v-model:selectedKey="selectedKey" :showLine="false" :replace-fields="{'id': 'key', 'title': 'title', 'children': 'children'}" @node-click="node_click">
        <template #title="{ data }">
          <div :class="[data.children&&data.children.length>0?'is-children':'end']"> {{ data.title }}</div>
        </template>
      </lay-tree>
    </div> 
    <div class="r-content">

    </div> -->
      <div class="top-btn"> <lay-button class="btn-add" type="primary" size="sm" @click="add" v-permissions="'permissions_add'">新增</lay-button></div>
      <!-- <lay-table ref="tableTreeRef" children-column-name="children" :columns="columns" :data-source="menuList" :default-toolbar="false" id="key" maxHeight="800px">
      <template v-slot:operator="{ row }">
        <lay-button type="primary" size="sm" @click="edit_trr(row)">修改</lay-button>
        <lay-button type="" size="sm">详情</lay-button>
        <lay-button type="danger" size="sm" @click="delete_tree(row.key)">删除</lay-button>
      </template>
    </lay-table> -->

      <el-table ref="table_tree" :data="menuList" style="width: 100%;" row-key="key" border lazy :load="load" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
        <el-table-column prop="title" label="权限名称" />
        <!-- <el-table-column prop="key" label="key" /> -->
        <el-table-column prop="" label="操作">
 
          <template #default="scope">
            <!-- <lay-button class="btn-add" type="primary" size="xs" @click="add" v-if="nowMenuBtnArr.includes('新增')">新增</lay-button> -->
            <lay-button class="btn-edit" type="primary" size="xs" @click="edit_trr(scope.row)" v-permissions="'permissions_edit'" >修改</lay-button>
            <lay-button class="btn-delete" type="danger" size="xs" @click="delete_tree(scope.row,scope)" v-permissions="'permissions_delete'" >删除</lay-button>
            <lay-button class="btn-view" type="" size="xs" @click="view_tree(scope.row)" v-permissions="'permissions_view'" >查看</lay-button>
          </template> 

        </el-table-column>
      </el-table>

      <!-- 弹层 -->
      <lay-layer v-model="layerIsShow" title="提示"   :area="['700px', '620px']" :btn="isAddEdit=='view'?[]:laerBtn" :shadeClose="false">
        <div style="padding: 20px 40px 20px 20px;">
          <lay-form :model="form" ref="layFormRef11">
            <lay-form-item label="权限名称" prop="permissionName">
              <lay-input v-model="form.permissionName" :disabled="isAddEdit=='view'"></lay-input>
            </lay-form-item>
            <lay-form-item label="权限编号" prop="permissionId">
              <lay-input v-model="form.permissionId" :disabled="isAddEdit=='view'"></lay-input>
            </lay-form-item>
            <lay-form-item label="图标" prop="permissionIcon">
              <lay-input v-model="form.permissionIcon" :disabled="isAddEdit=='view'"></lay-input>
            </lay-form-item>
            <lay-form-item label="是否显示" prop="permissionIshide">
              <lay-select v-model="form.permissionIshide" placeholder="请选择" style="width: 100%;" :disabled="isAddEdit=='view'">
                <lay-select-option value="1" label="显示"></lay-select-option>
                <lay-select-option value="0" label="隐藏"></lay-select-option>
              </lay-select>
            </lay-form-item>
            <lay-form-item label="排序等级" prop="permissionLevel">
              <lay-input v-model="form.permissionLevel" :disabled="isAddEdit=='view'"></lay-input>
            </lay-form-item>
            <lay-form-item label="父级ID" prop="permissionParentId">
              <!-- <lay-input v-model="form.permissionParentId" :disabled="isAddEdit=='view'"></lay-input> -->
              <lay-tree-select v-model="form.permissionParentId" :data="allMenuData" placeholder="请选择" :allow-clear="true" :search="true" :multiple="false" :replaceFields="{id:'key'}"
                style="width: 100%;" :disabled="isAddEdit=='view'"></lay-tree-select>
            </lay-form-item>

            <lay-form-item label="类型" prop="permissionType">
              <!-- <lay-input v-model="form.permissionType"></lay-input> -->
              <lay-select v-model="form.permissionType" placeholder="请选择" style="width: 100%;" :disabled="isAddEdit=='view'">

                <lay-select-option value="0" label="父菜单"></lay-select-option>
                <lay-select-option value="1" label="子菜单"></lay-select-option>
                <lay-select-option value="2" label="按钮"></lay-select-option>
                <lay-select-option value="3" label="列表"></lay-select-option>
              </lay-select>
            </lay-form-item>

            <lay-form-item label="url路径" prop="permissionUrl">
              <lay-input v-model="form.permissionUrl" :disabled="isAddEdit=='view'"></lay-input>
            </lay-form-item>

          </lay-form>
        </div>
      </lay-layer>

    </div>
  </div>
</template>

<script setup lang="ts">
import http from "@/http/index";
import { layer } from "@layui/layui-vue";
import { nextTick, onMounted, reactive, ref } from "vue";

import { useCounterStore } from "@/current";
import { storeToRefs } from "pinia"; // cnpm i pinia --save  2.1.3
const store = useCounterStore();
const { menuList, nowMenuBtnArr } = storeToRefs(store); //  数据
const { get_menu_list } = store; //方法

// 添加 ? 修改？ 查看
const isAddEdit = ref("");
// 树形数据
const treeList = ref([]);
const selectedKey = ref(1);
// 控制弹层
const layerIsShow = ref(false);
const form = ref({
  permissionComponet: "",
  permissionIcon: "",
  permissionId: "",
  permissionIshide: "",
  permissionKey: "",
  permissionLevel: 0,
  permissionName: "",
  permissionParentId: "",
  permissionType: "0",
  permissionUrl: "",
});

const columns = ref([
  { title: "title", key: "title" },
  { title: "key(id)", key: "key" },
  { title: "操作", key: "operator", customSlot: "operator" },
]);
const dataSource = ref([]);

const node_click = (data) => {
  if (!data.children || data.children.length <= 0) {
    console.log(data);
    get_list_detail(data.key);
  }
};

const table_tree = ref();
const loadMap = new Map();
const load = async (row, treeNode, resolve) => {
  loadMap.set(row.key, { row, treeNode, resolve });
  console.log(row, treeNode, resolve);
  // const res = await http.corsApi("/secPermission/page", "get", {
  //   pageNo: 1,
  //   pageSize: 100,
  //   permissionParentId: row.value,
  // });
  // console.log(res);
  // let data = res.data.list;
  // data.map((item) => {
  //   item["key"] = item.permissionId;
  //   item["value"] = item.permissionId;
  //   item["title"] = item.permissionName;
  // });

  const res = await get_load_data(row.value);
  console.log(res);

  if (res) {
    resolve(res);
  }
  // setTimeout(() => {
  //   resolve([
  //     {
  //       id: 31,
  //       date: "2016-05-01",
  //       name: "wangxiaohu",
  //       address: "No. 189, Grove St, Los Angeles",
  //     },
  //     {
  //       id: 32,
  //       date: "2016-05-01",
  //       name: "wangxiaohu",
  //       address: "No. 189, Grove St, Los Angeles",
  //     },
  //   ]);
  // }, 1000);
};

const get_load_data = async (id) => {
  const res = await http.corsApi("/secPermission/page", "get", {
    pageNo: 1,
    pageSize: 100,
    permissionParentId: id,
  });
  console.log(res);
  let data = res.data.list;
  data.map((item) => {
    item["key"] = item.permissionId;
    item["value"] = item.permissionId;
    item["title"] = item.permissionName;
  });

  return data;
};

// 添加
const add = async () => {
  isAddEdit.value = "add";
  layerIsShow.value = true;

  form.value.permissionComponet = "";
  form.value.permissionIcon = "";
  form.value.permissionId = "";
  form.value.permissionIshide = "";
  form.value.permissionKey = "";
  form.value.permissionLevel = 0;
  form.value.permissionName = "";
  form.value.permissionParentId = "";
  form.value.permissionType = "0";
  form.value.permissionUrl = "";
};

const table_row = ref([]);
// 表格修改
const edit_trr = (row) => {
  console.log(row);
  isAddEdit.value = "edit";
  get_list_detail(row.key);
  console.log(table_tree.value);
  console.log(loadMap.get(row.permissionParentId));
  table_row.value = row;

  layerIsShow.value = true;
};

// 删除
const delete_tree = async (row, scope) => {
  console.log(scope);
  console.log(row);

  layer.confirm("确认要删除吗？", {
    btn: [
      {
        text: "确认",
        callback: async (id) => {
          const res = await http.corsApi("/secPermission/batch", "delete", [row.key]);
          console.log(res);
          if (res.data) {
            await get_menu_list();

            if (row.permissionType > 1) {
              await refreshTreeNode(row.permissionParentId);
            }

            await layer.confirm("删除成功", { icon: 1 });
          }
          layer.close(id);
        },
      },
      {
        text: "取消",
        callback: (id) => {
          layer.close(id);
        },
      },
    ],
  });
};

// 弹层按钮
const laerBtn = ref([
  {
    text: "确认",
    callback: async () => {
      console.log(form.value);

      if (isAddEdit.value == "add") {
        const res = await http.corsApi("/secPermission", "post", form.value);
        console.log(res);
        if (res.data) {
          // nextTick(() => {
          //   // refreshTreeNode(table_row.value.permissionParentId, [res]);
          //   loadMap.get(form.value.permissionParentId).resolve(res);
          // });
          // window.location.reload()

          if (form.value.permissionType > 1) {
            await refreshTreeNode(form.value.permissionParentId);
          }

          await get_menu_list();
          await layer.confirm("添加成功", { icon: 1 });
          layerIsShow.value = false;
        }
      } else if (isAddEdit.value == "edit") {
        const res = await http.corsApi("/secPermission", "put", form.value);
        console.log(res);
        if (res.data) {
          await get_menu_list();

          if (table_row.value.permissionType > 1) {
            await refreshTreeNode(table_row.value.permissionParentId);
          }

          await layer.confirm("修改成功", { icon: 1 });

          layerIsShow.value = false;
        }
      }
    },
  },
  {
    text: "取消",
    callback: () => {
      layerIsShow.value = false;
    },
  },
]);

// 查看  详情
const view_tree = (row) => {
  isAddEdit.value = "view";
  layerIsShow.value = true;
  table_row.value = row;
  get_list_detail(row.key);
};

// 菜单数据
const get_list = async () => {
  // const res = await http.corsApi("/secPermission/treeSelectByResKey", "get", {});
  // console.log(res);
  // treeList.value = res.data[0].children;
  // console.log(treeList.value);

  await get_menu_list();
};
// 某个菜单数据的详情
const get_list_detail = async (id) => {
  const res = await http.corsApi(`/secPermission/${id}`, "get", {});
  console.log(res);
  form.value = res.data;
};

const refreshTreeNode = async (id) => {
  const res = await get_load_data(id);
  console.log(res);

  nextTick(() => {
    // refreshTreeNode(id, [res]);
    loadMap.get(id).resolve(res);
  });

  // if (loadMap.get(id)) {
  //   loadMap.get(id).resolve(data);
  //   /*报错部分修改*/
  //   // table.value.store.states.lazyTreeNodeMap.value[item.id].push({});
  //   // load(row, treeNode, resolve);
  // }
};

const allMenuData = ref([]);
// 页面初始化
onMounted(() => {
  get_list();

  console.log(menuList.value);

  // 父级id
  allMenuData.value = [
    {
      key: "TOP",
      title: "最顶层",
      value: "TOP",
      children: null,
    },
    ...menuList.value,
  ];

  console.log(allMenuData.value);
  
});
</script>

<style scoped lang="scss">
.permissions {
  display: flex;
  flex-direction: column;
  .top-btn {
    margin-bottom: 15px;
  }
  .l-tree {
    width: 150px;

    .is-children {
      color: #555;
    }
  }
}
</style>